package com.hl233.gateway.filter;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.hl233.common.constant.Constants;
import com.hl233.gateway.properties.AuthProperties;
import com.hl233.gateway.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关鉴权
 *
 * @author 张振强15065206763
 * @create 2024-09-18
 */
@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;
    @Autowired
    private JwtUtil jwtUtil;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();
        //判断是否需要做登录拦截
        System.out.println("渠道header" + headers);
//        if (isExcloude(request.getPath().toString())) {
//            return chain.filter(exchange);
//        }
        String authorization = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if (StringUtils.isBlank(authorization)) {
            authorization = "";
        }
        Claims claims = null;
        try {
            claims = jwtUtil.parseToken(authorization);
        } catch (Exception e) {
            //拦截设置响应状态
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        String userId = claims.get(Constants.DETAILS_USER_ID, Integer.class) + "";
        System.out.println("取不到userid???"+userId);
        ServerWebExchange serverWebExchange = exchange.mutate().request(builder -> builder.header(Constants.DETAILS_USER_ID, userId)).build();

        return chain.filter(serverWebExchange);
    }

    private boolean isExcloude(String path) {
        for (String pathPattern : authProperties.getExcludePaths()){

            antPathMatcher.match(pathPattern,path);
        }
        return false;
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }
}
